package com.haoniu.web.controller.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.oss.ServiceException;
import com.haoniu.common.base.AjaxResult;
import com.haoniu.common.utils.DateUtils;
import com.haoniu.common.utils.sms.SmsUtil;
import com.haoniu.framework.web.service.RedisService;
import com.haoniu.pay.alipay.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import com.haoniu.common.config.Global;
import com.haoniu.common.utils.file.FileUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 通用请求处理
 *
 * @author haoniu
 */
@Controller
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Value("${sms.phone}")
    private String phone;

    @Value("${sms.maxCount}")
    private Integer maxCount;

    @Value("${sms.expireTime}")
    private Integer expireTime;

    @Autowired
    private RedisService redisService;


    @RequestMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
        try {
            String filePath = Global.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 获取手机验证码
     *
     * @param phone
     * @param type  短信类型 ： register  注册短信, updatePwd 修改密码短信 updatePayPwd 更新支付密码
     * @throws ServiceException
     */
    @RequestMapping(value = "common/getMsgCode", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public AjaxResult getMsgCode() throws ServiceException {
        String nowYmd = DateUtils.getDate();
        String msgCodeKey = nowYmd+":getMsgCode:" + phone;
        Object o = redisService.get(msgCodeKey);
        if(o!=null){
            Integer msgCount = (Integer)o;
            if(msgCount>maxCount){
                return AjaxResult.error("获取短信次数超限!");
            }
        }
        String authCode = RandomUtil.numberId(6);
        SmsUtil.send(phone,authCode);

        redisService.setConfig("authCode:"+phone,authCode,expireTime);
        redisService.incr(msgCodeKey, 1);
        return AjaxResult.success();
    }

    public String setFileDownloadHeader(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE")) {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        } else if (agent.contains("Chrome")) {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }
}
